# -*- coding: utf-8 -*-

"""
Date: 2023/2/24 15:42
Author: Darker
"""
import os.path
from typing import Dict, NoReturn, Text, Any

import attr

from config import conf
from utils import dump, load


@attr.s(auto_attribs=True)
class CacheUtils(object):

    def read_cache(self, ) -> Dict:
        """
        读取缓存文件内容
        :return: 缓存文件详情
        """
        if not os.path.exists(conf.cacheFilePath):
            self.write_cache({})
        return load(conf.cacheFilePath)

    def write_cache(self, cacheData: Dict) -> NoReturn:
        """
        将数据写入缓存文件
        :return: NoReturn
        """
        return dump(conf.cacheFilePath, cacheData)

    def get_option(self, option: Text) -> Any:
        """
        获取缓存文件中的某个具体的缓存值
        :param option: key
        :return: Any
        """
        cacheDict = self.read_cache()
        if isinstance(cacheDict, Dict):
            return cacheDict.get(option)

    @property
    def cookies(self):
        cookies = self.get_option("cookies")
        data = {}
        if isinstance(cookies, str):
            if "=" in cookies:
                for item in cookies.split(";"):
                    k, v = item.split("=")
                    data[k] = v
        return data


cacheUtils = CacheUtils()
